package com.example.todaynews.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.example.todaynews.bean.NewsInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wj on 2016/8/24.
 */
public class NewsDataUtils {
    private NewsDataHelper helper;
    private static final String TAG = "NewsDataUtils";

    public NewsDataUtils(Context context) {
        helper = new NewsDataHelper(context);
    }

    public void delete() {
        SQLiteDatabase db = helper.getReadableDatabase();
        db.delete(NewsDataHelper.TABLE_NAME, null, null);
        db.close();
    }

    public void saveNews(List<NewsInfo> list) {
        SQLiteDatabase db = helper.getReadableDatabase();
        for (NewsInfo info : list) {
            ContentValues values = new ContentValues();
            values.put("title", info.getTitle());
            values.put("thumbnail_pic_s", info.getThumbnail_pic_s());
            values.put("thumbnail_pic_s02", info.getThumbnail_pic_s02());
            values.put("thumbnail_pic_s03", info.getThumbnail_pic_s03());
            values.put("date", info.getDate());
            values.put("realtype", info.getRealtype());
            values.put("url", info.getUrl());
            db.insert(NewsDataHelper.TABLE_NAME, null, values);
        }
        db.close();
    }

    public List<NewsInfo> getAllNews() {
        SQLiteDatabase db = helper.getReadableDatabase();
        List<NewsInfo> list = new ArrayList<NewsInfo>();
        Cursor cursor = db.rawQuery("select * from todaynews", null);
        if (cursor != null && cursor.getColumnCount() > 0) {
            while (cursor.moveToNext()) {
                NewsInfo info = new NewsInfo();
                info.setTitle(cursor.getString(0));
                info.setThumbnail_pic_s(cursor.getString(1));
                info.setThumbnail_pic_s02(cursor.getString(2));
                info.setThumbnail_pic_s03(cursor.getString(3));
                info.setDate(cursor.getString(4));
                info.setRealtype(cursor.getString(5));
                info.setUrl(cursor.getString(6));
                list.add(info);
            }
        }
        cursor.close();
        db.close();
        return list;
    }
}
